<template>
  <el-dialog
    v-el-drag-dialog
    class="tempDialog"
    :title="$t('选择模版')"
    :visible="visible"
    width="900px"
    :close-on-click-modal="false"
    @update:visible="updateVisible"
    append-to-body
  >
    <div class="search-row">
      <div class="search-item mr-15">
        <span class="label">{{ $t('名称') }}</span>
        <el-input
          v-model="search.name"
          class="input-240"
          maxlength="20"
          autocomplete="off"
          :show-word-limit="false"
          clearable
        ></el-input>
      </div>
      <div class="search-item mr-15">
        <el-button type="primary" size="small" @click="getTempList">{{ $t('搜索') }}</el-button>
      </div>
      <div class="search-item mr-15">
        <el-select-tree
          class="input-240"
          :data="treeData"
          check-strictly
          :props="{
            value: 'id',
            label: 'name',
            children: 'children',
          }"
          v-model="search.folderId"
          @change="folderChange"
        ></el-select-tree>
      </div>
      <div class="search-item">
        <el-select class="input-200" v-model="displayType">
          <el-option
            v-for="d in displayTypeOpts"
            :key="d.value"
            :value="d.value"
            :label="$t(d.label)"
          ></el-option>
        </el-select>
      </div>
    </div>
    <div class="data-box">
      <mini-panel
        ref="miniPanel"
        :datas="tempData"
        v-show="displayType === '1'"
        :options="{
          noPop: true,
          sizeType: 'medium',
        }"
        @dbClick="dbClick"
      ></mini-panel>
      <list
        ref="list"
         height="calc(35vh)"
        v-show="displayType === '2'"
        :init-cols-props.sync="initColsProps"
        :list-data="tempData"
        :list-cols="listCols"
        :highlight="true"
        :table-tag="tableName"
        :action-opts="actionOpts"
        @row-click="handleRowClick"
        @sort="handleListSort"
        @cell-double-click="dbClick"
      >
        <template slot="auditStateSlot" slot-scope="{ row }">
          {{ row.auditState | getStateName(te) }}
        </template>
        <template slot="validitySlot" slot-scope="{ row }">
          {{ row.validity ? '有效' : '无效' }}
        </template>
      </list>
    </div>

    <div slot="footer" class="dialog-footer">
      <bs-confirm-button-icon size="mini" @click.native="okClick" />
      <bs-cancel-button-icon size="mini" @click.native="cancelClick" />
    </div>
  </el-dialog>
</template>

<script>
import MiniPanel from '../../components/MiniPanel'
import List from '@/components/List'
import MediaApi from '@/api/media'

import {createNamespacedHelpers} from 'vuex'
const {mapGetters, mapActions} = createNamespacedHelpers('media')

export default {
  filters: {
    getStateName(v,te) {
      switch (Number(v)) {
        case 0:
          return te('待审核')
        case 1:
          return te('已通过')
        case 2:
          return te('已拒绝')
        default:
          return ''
      }
    },
  },
  components: {
    MiniPanel,
    List,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const headerContextMenus = {
      width: '120px',
      items: ['sortUp', 'sortDown', 'line', 'cols'],
    }

    return {
      activeId: '', // 已选模版
      tempData: [],
      listCols: [
        { label: '名称', prop: 'name', headerContextMenus },
        { label: '有效性', prop: 'validity', headerContextMenus, slot: true },
        { label: '审核', prop: 'auditState', headerContextMenus, slot: true },
        { label: '宽', prop: 'width', headerContextMenus },
        { label: '高', prop: 'height', headerContextMenus },
        { label: '创建时间', prop: 'createdAt', headerContextMenus },
      ],
      initColsProps: [
        'name',
        'validity',
        'auditState',
        'width',
        'height',
        'createdAt',
      ],
      actionOpts: { show: false },
      displayType: '1', // 1 缩略图 2 列表
      tableName: 'TempDialogTableList',
      displayTypeOpts: [
        {
          value: '1',
          label: '缩略图',
        },
        {
          value: '2',
          label: '详细信息',
        },
      ],
      search: {
        name: '',
        folderId: 0,
      },
      sort: {
        orders: '',
        sortField: '',
      },
      sortFieldMap: {
        name: 1,
        validity: 9,
        auditState: 4,
        width: 5,
        height: 6,
        createdAt: 11,
      },
      listCurrRow: null,
      ownerUserId: '',
    }
  },
  computed: {
    ...mapGetters(['menuTree']),
    treeData() {
      return this.everyAddId(this.menuTree(2))
    }
  },
  watch: {
    visible(v) {
      if (v) {
        this.getTempList()
      }
    },
  },
  created() {
    this.getTempTreeData()
    this.initBottomTree()
    this.fetchOtherData()
  },
  methods: {
    ...mapActions(['setMenuTree']),
    everyAddId(arr) {
      return arr.map(item => {
        let out = {}
        let children = []
        if (item.children && item.children instanceof Array && item.children.length > 0) {
          children = this.everyAddId(item.children)
        }
        out = {
          ...item
        }
        if (!out.id && out.id !== 0) {
          out.id = `0#${out.name}`
        }
        if (children.length > 0) out.children = children
        return out
      })
    },
    updateVisible(v) {
      this.$emit('update:visible', v)
    },
    folderChange(val, data) {
      this.ownerUserId = (data._isSub || data._isOther) ? data.ownerUserId : ''
      this.getTempList()
    },
    handleRowClick(row) {
      this.listCurrRow = row
    },
    async dbClick(item) {
      const res = await this.getTempInfoById(item.id)

      if (res) {
        this.updateVisible(false)
        this.$emit('close', res)
      } else {
        this.$alert('提示', '获取此模板信息失败，请更换模板')
      }
    },
    async okClick() {
      // this.fetching = true
      // if (this.opType === '1') {
      //   this.$emit('addClick', this.self_form, this.fetchingEndCb)
      // } else if (this.opType === '2') {
      //   this.$emit('updateClick', this.self_form, this.fetchingEndCb)
      // } else {
      //   this.updateVisible(false)
      // }
      let _temp
      if (this.displayType === '1') {
        _temp = this.$refs.miniPanel.getActiveItem()
      } else {
        _temp = this.listCurrRow
      }

      if (!_temp) return this.$alert('提示', '请选一个模板')

      const res = await this.getTempInfoById(_temp.id)

      if (res) {
        this.updateVisible(false)
        this.$emit('close', res)
      } else {
        this.$alert('提示', '获取此模板信息失败，请更换模板')
      }
    },
    cancelClick() {
      this.updateVisible(false)
    },
    handleListSort({ type, prop }) {
      if (this.sortFieldMap[prop]) {
        this.sort = {
          sortField: this.sortFieldMap[prop],
          orders: type.toLowerCase(),
        }
        this.getTempList()
      }
    },
    async getTempList() {
      try {
        let params = {
          current: 1,
          size: 9999,
        }
        params.folderId = typeof this.search.folderId === 'string' ? 0 : this.search.folderId
        if (this.search.name) {
          params.queryType = 1
          params.queryParam = this.search.name
        }
        if (this.sort.sortField) {
          params.sortField = this.sort.sortField
          params.orders = this.sort.orders
        }
        params.auditState = 1
        if (this.ownerUserId) params.ownerUserId = this.ownerUserId
        const res = await MediaApi.getTemplate(params)
        this.tempData = res.records.filter(item => {
          return item.validity
        })
      } catch (error) {
        console.log('error', error)
      }
    },
    async getTempTreeData() {
      try {
        const res = await MediaApi.getCatalogue({ type: 2 })
        this.treeData[0].children = res
      } catch (error) {
        console.log('error', error)
      }
    },
    async initBottomTree() {
      try {
        const res = await MediaApi.getFollow({ type: 2 })
        // this.treeData[1].children = res[0]   10/24  seven modify
        this.setMenuTree({
          treeData: res,
          type: 2,
          isSub: true
        })
      } catch (error) {
        console.log('error', error)
      }
    },
    // 获取其他资源
    async fetchOtherData() {
      const res = await  MediaApi.getOtherMedia({type: 2})
      this.setMenuTree({
        otherMediaTreeData: res,
        type: 2
      })
    },

    async getTempInfoById(id) {
      try {
        const res = await MediaApi.loadTemplateById({id})
        return res
      } catch (error) {
        console.log('error', error)
        return false
      }
    },

    te(arg) {
      const hasKey = this.$te(arg)
      if (hasKey) {
        const result = this.$t(arg)
        return result
      }
      return arg
    },
  },
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';

$info-row-h: 57px;
$border-style: 1px solid $bg-e9;

  .list {
    margin: 15px;
  }
  .tempDialog {
    ::v-deep .el-dialog__body {
      padding: 0;
    }

  ::v-deep .el-dialog__header {
    border-bottom: $border-style;
  }

  ::v-deep .el-dialog__footer {
    padding: 0;
    border-top: none;
  }
}

.input-240 {
  width: 290px;
}
.input-200 {
  width: 200px;
}
.mr-15 {
  margin-right: 15px;
}

.search-row {
  height: 76px;
  display: flex;
  align-items: center;
  justify-content: center;

  .search-item {
    display: flex;
    align-items: center;
    .label {
      width: 42px;
    }
  }
}

.data-box {
  border: $border-style;
  width: 840px;
  height: 380px;
  margin: 0 auto;
  overflow-y: auto;
}

.dialog-footer {
  height: 76px;
  line-height: 76px;
  border-top: $border-style;
  margin-top: 18px;
}
</style>
